package com.xnx.bincker.leader.core.autorun;

import com.xnx.bincker.leader.domain.Role;
import com.xnx.bincker.leader.domain.User;
import com.xnx.bincker.leader.service.AuthorityService;
import com.xnx.bincker.leader.service.RoleService;
import com.xnx.bincker.leader.service.UserService;
import com.xnx.bincker.leader.utils.StringUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashSet;

/**
 * 用户初始化
 */
@Log4j2
@Component
public class UserInitialization implements CommandLineRunner {
	private final UserService userService;
	private final RoleService roleService;
	private final AuthorityService authorityService;
	private final PasswordEncoder passwordEncoder;

	@Autowired
	public UserInitialization(
			UserService userService,
			RoleService roleService,
			AuthorityService authorityService,
			PasswordEncoder passwordEncoder
	) {
		this.userService = userService;
		this.roleService = roleService;
		this.authorityService = authorityService;
		this.passwordEncoder = passwordEncoder;
	}

	@Override
	public void run(String... args) throws Exception {
		initializationRole();
		for (int i = 0; i < args.length; i++) {
			String arg = args[i];
			if (arg.equalsIgnoreCase("--create-super-admin")) {
				if(args.length == i+1) throw new Exception("请输入超级管理员用户名");
				String username = args[i+1];
				if(StringUtils.isEmpty(username)) throw new Exception("请输入超级管理员用户名");
				createSuperAdmin(username);
				return;
			}
		}
	}

	/**
	 * 角色初始化
	 */
	private void initializationRole(){
//		普通用户角色
		Role userRole = roleService.findByCode("user").orElseGet(()->{
			Role r = new Role();
			r.setCode("user");
			r.setName("普通用户");
			r.setRemark("普通用户角色");
			return roleService.save(r);
		});
//		管理员角色
		Role adminRole = roleService.findByCode("admin").orElseGet(()->{
			Role r = new Role();
			r.setCode("admin");
			r.setName("管理员");
			r.setRemark("后台管理员");
			return roleService.save(r);
		});
//		超级管理员
		Role superAdminRole = roleService.findByCode("super_admin").orElseGet(()->{
			Role r = new Role();
			r.setCode("super_admin");
			r.setName("超级管理员");
			r.setRemark("超级管理员");
			return roleService.save(r);
		});
		superAdminRole.setAuthorities(new HashSet<>(authorityService.findAll()));
		roleService.save(superAdminRole);
	}

	/**
	 * 创建超级管理员
	 * @param username 用户名
	 */
	private void createSuperAdmin(String username){
		User admin = userService.findUserByUsername(username).orElse(new User());
		admin.setUsername(username);
		admin.setNickname(username);
		String password = StringUtils.getRandomString(12);
		admin.setPassword(passwordEncoder.encode(password));
		admin.getRoles().add(roleService.findByCode("super_admin").orElseThrow(()->new RuntimeException("超级管理员角色不存在")));
		admin.getRoles().add(roleService.findByCode("admin").orElseThrow(()->new RuntimeException("管理员角色不存在")));
		admin.getRoles().add(roleService.findByCode("user").orElseThrow(()->new RuntimeException("普通角色不存在")));
		admin.setEnabled(true);
		admin.setLocked(false);
		userService.save(admin);
		log.info("超级管理员【"+username+"】密码为：" + password);
	}
}
